import axios from 'axios'
import qs from 'qs'
import { AXIOS_BASE_CONFIG } from './config'
 
import type { AxiosRequestConfig, AxiosResponse, AxiosInstance } from 'axios'
 
// import { message } from 'ant-design-vue'
 
// import * as TYPES from '@/types/mutation-type'
import useStorage from '@/hooks/useStorage'
import { userStore } from '@/store/modules/userStore'
 
type axiosResponse<T = any> = {
  message: string
  code: number
  success: boolean
}
 
const handleError = (error: any) => {
  // const {
  //   data: { message },
  // } = error.response
  // message.destroy()
  // message.error(message ? message : '请求失败,请重新刷新页面')
  // return Promise.reject(error)
}
 
class Request {
  private instance: AxiosInstance
  constructor(config: AxiosRequestConfig = {}) {
    if(config.agvAPI){
      AXIOS_BASE_CONFIG.baseURL = ''
      config.headers = {}
      config.headers['token'] =  'admin123'
      config.headers['name'] =  'lx-script'
    }
    this.instance = axios.create({ ...AXIOS_BASE_CONFIG, ...config })
    this.initInstance()
  }
 
  /**
   * @method 初始化拦截器
   */
  private initInstance() {
    /**
     * @method 请求拦截器
     */
    this.instance.interceptors.request.use((config: AxiosRequestConfig) => {

      const {token} = userStore()
      if (token && !config.agvAPI) {
        config.headers['Authorization'] = 'Bearer ' + token
      }
      if (['GET', 'get'].includes(config.method!) && config.data) {
        config.url += '?' + qs.stringify(config.data ?? '')
      }
      
      return config
    }, handleError)
 
    /**
     * @method 响应拦截器
     */
    this.instance.interceptors.response.use((response: AxiosResponse<axiosResponse>) => {
      const {LOGIN,setToken} = userStore()
      if (!(response.data.type=='success') && !response.data.state) {
        if([401].includes(response.data.code)){
          // console.log('AA')
          setToken()
          setTimeout(() => {
            window.location.reload()
          }, 500)
        }
        if ([403, 505].includes(response.data.code)) {
          setTimeout(() => {
            window.location.replace(window.location.origin)
          }, 500)
        }
       
        return Promise.reject(response.data)
      }
 
      return Promise.resolve(response.data)
    }, handleError)
  }
 
  /**
   * @method 请求
   * @param config 请求配置项
   */
  private request<D = any>(config: AxiosRequestConfig) {
    return new Promise<axiosResponse<D>>(async (resolve, reject) => {
      try {
        const res = await this.instance.request<axiosResponse<D>, axiosResponse<D>>(config)
        resolve(res)
      } catch (error) {
        console.log('error', error)
        reject(error)
      }
    })
  }
 
  /**
   * @method GET请求
   * @param config 请求配置项
   */
  public GET<R>(config: AxiosRequestConfig) {
    return this.request<R>({ ...config, method: 'GET' })
  }
 
  /**
   * @method POST请求
   * @param config 请求配置项
   */
  public POST<R>(config: AxiosRequestConfig) {
    return this.request<R>({ ...config, method: 'POST' })
  }
 
  /**
   * @method PUT请求
   * @param config 请求配置项
   */
  public PUT<R>(config: AxiosRequestConfig) {
    return this.request<R>({ ...config, method: 'PUT' })
  }
 
  /**
   * @method DELETE请求
   * @param config 请求配置项
   */
  public DELETE<R>(config: AxiosRequestConfig) {
    return this.request<R>({ ...config, method: 'DELETE' })
  }
}
 
export default Request